<?php

namespace app\admin\model;

use think\Model;


class ClothmakingRecipe extends Model
{





    // 表名
    protected $name = 'clothmaking_recipe';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'ingredient_details_text'
    ];

    // JSON字段
    protected $json = ['ingredient_details'];
    protected $jsonAssoc = true;

    // 友好显示
    public function getIngredientDetailsTextAttr($value, $data)
    {
        if (isset($data['ingredient_details']) && is_array($data['ingredient_details'])) {
            $arr = [];
            foreach ($data['ingredient_details'] as $ingredientId => $quantity) {
                // 根据配料ID获取配料名称
                $ingredientName = $this->getIngredientNameById($ingredientId);
                $arr[] = $ingredientName . ':' . $quantity . 'kg';
            }
            return implode('，', $arr);
        }
        return '';
    }

    // 根据配料ID获取配料名称
    protected function getIngredientNameById($ingredientId)
    {
        try {
            $ingredient = \app\admin\model\ClothmakingRaw::where('id', $ingredientId)->find();
            return $ingredient ? $ingredient->name : '未知配料(' . $ingredientId . ')';
        } catch (\Exception $e) {
            return '未知配料(' . $ingredientId . ')';
        }
    }










}
